package com.example.springboot.service;

import com.example.springboot.dto.DashboardStatsDTO;
import com.example.springboot.mapper.DashboardMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
public class DashboardService {

    private static final Logger logger = LoggerFactory.getLogger(DashboardService.class);

    @Autowired
    private DashboardMapper dashboardMapper;

    public DashboardStatsDTO getDashboardStats(HttpServletRequest request) {
        String role = request.getHeader("Role");
        String username = decodeUsername(request.getHeader("Username"));

        validateInput(role, username);

        DashboardStatsDTO stats = new DashboardStatsDTO();
        Integer adminId = null;
        String adminRole = dashboardMapper.findAdminRoleByUsername(username);

        if (adminRole == null) {
            logger.error("No role found for username: {}", username);
            throw new IllegalArgumentException("管理员用户不存在或角色未定义");
        }

        if (!"super".equals(adminRole)) {
            adminId = dashboardMapper.findAdminIdByUsername(username);
            if (adminId == null) {
                logger.error("No admin ID found for username: {}", username);
                throw new IllegalArgumentException("无法获取管理员 ID，用户名可能不存在");
            }
            logger.info("Fetching stats for common admin with adminId: {}", adminId);
        } else {
            logger.info("Fetching stats for super admin");
        }

        stats.setTotalUsers(dashboardMapper.getTotalUsers(adminId));
        stats.setTotalMerchants(dashboardMapper.getTotalMerchants(adminId));
        stats.setTotalSelfServicePoints(dashboardMapper.getTotalSelfServicePoints(adminId));
        stats.setTotalOrders(dashboardMapper.getTotalOrders(adminId));
        stats.setTotalEarnings(dashboardMapper.getTotalEarnings(adminId));
        stats.setActiveDevices(dashboardMapper.getActiveDevices(adminId));
        stats.setMaintenanceDevices(dashboardMapper.getMaintenanceDevices(adminId));
        stats.setLastUpdated(new Date());

        return stats;
    }

    private void validateInput(String role, String username) {
        if (username == null || username.trim().isEmpty()) {
            logger.error("Username is null or empty");
            throw new IllegalArgumentException("Username header is required");
        }
        if (role == null || role.trim().isEmpty()) {
            logger.error("Role is null or empty");
            throw new IllegalArgumentException("Role header is required");
        }
    }

    private String decodeUsername(String username) {
        if (username == null) {
            return null;
        }
        try {
            return URLDecoder.decode(username, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            logger.warn("Failed to decode username: {}, using original value", username, e);
            return username;
        }
    }
}